package com.smf.lsc.resource.security.resource.filter;

import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.smf.lsc.security.util.PermisUrlCheckUtil;

/**
 * 白名单去除Authorization header,便于通过oauth2的token校验
 * Created on 2021/11/19.
 *
 * @author ln
 * @since 1.0
 */
@Component("permitAuthenticationFilter")
public class PermitAuthenticationFilter extends OncePerRequestFilter {
	
	@Value("${security.oauth2.permis-urls:''}")
    private String permisUrls;
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

	    if (PermisUrlCheckUtil.matches(request.getRequestURI(),permisUrls)) {

	        request = new HttpServletRequestWrapper(request) {
	            private Set<String> headerNameSet;

	            @Override
	            public Enumeration<String> getHeaderNames() {
	                if (headerNameSet == null) {
	                    // first time this method is called, cache the wrapped request's header names:
	                    headerNameSet = new HashSet<>();
	                    Enumeration<String> wrappedHeaderNames = super.getHeaderNames();
	                    while (wrappedHeaderNames.hasMoreElements()) {
	                        String headerName = wrappedHeaderNames.nextElement();
	                        if (!"Authorization".equalsIgnoreCase(headerName)) {
	                            headerNameSet.add(headerName);
	                        }
	                    }
	                }
	                return Collections.enumeration(headerNameSet);
	            }

	            @Override
	            public Enumeration<String> getHeaders(String name) {
	                if ("Authorization".equalsIgnoreCase(name)) {
	                    return Collections.<String>emptyEnumeration();
	                }
	                return super.getHeaders(name);
	            }

	            @Override
	            public String getHeader(String name) {
	                if ("Authorization".equalsIgnoreCase(name)) {
	                    return null;
	                }
	                return super.getHeader(name);
	            }
	        };

	    }
	    filterChain.doFilter(request, response);
	}
	
}